'''
zabbixAPl:
1.调用地址 http://x.x.x.x/zabbix/api_jsonrpc.php
2.调用方法，http协议post
第三方模块:requests
3. 请求、响应必须是json格式与字典相似,但得转换
{key:value , key:value}

content_Type: application/json
可以去官网查看
'''

import json
import sys

import requests

zabbix_api_url = "http://192.168.106.133/zabbix/api_jsonrpc.php"
zabbix_api_user = "Admin"
zabbix_api_password = "zabbix"

# 登录zabbix 获取令牌
def get_zabbix_token():

    #请求头 固定值
    head = {"Content-Type":"application/json"}

    # 请求方法与数据
    data = {
            "jsonrpc": "2.0",
            "method": "user.login",
            "params": {
                "user": zabbix_api_user,
                "password": zabbix_api_password
            },
            "id": 1
        }

    # 发送请求获取密钥
    res = requests.post(url=zabbix_api_url,data=json.dumps(data),headers=head)
    zabbix_api_token = json.loads(res.text).get("result")
    return zabbix_api_token


def get_host_ID():
    token = get_zabbix_token()
    head = {"Content-Type": "application/json"}

    data ={
           "jsonrpc": "2.0",
           "method": "host.get",
           "params": {
               "output": [
                   "hostid",
                   "host"
               ],
               "selectInterfaces": [
                   "interfaceid",
                   "ip"
               ]
           },
           "id": 2,
           "auth": token
       }

    res = requests.post(url=zabbix_api_url,data=json.dumps(data),headers=head)

    host_id = json.loads(res.text).get("result")[1].get("hostid")
    interface_id = json.loads(res.text).get("result")[1].get("interfaces")[0].get("interfaceid")

    return host_id,interface_id

    # 创建监控项
def  ItemCreate():
    token = get_zabbix_token()
    host_id,interface_id = get_host_ID()

    head = {"Content-Type": "application/json"}
    data = {
           "jsonrpc": "2.0",
           "method": "item.create",
           "params": {
               "name": "测试1",
               "key_": "vfs.fs.size[/root]",
               "hostid": host_id,
               "type": 0,
               "value_type": 3,
               "interfaceid": interface_id,
               "delay": "30s"
           },
           "auth": token,
           "id": 1
       }

    res = requests.post(url=zabbix_api_url,data=json.dumps(data),headers=head)
    if "error" in res.text:
        print("创建监控项失败！！")
        print(res.text)
        sys.exit()
    else:
        print("创建监控项成功！！")


if __name__ == '__main__':
    ItemCreate()